﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using DTC.Database;
using DTC.Validations;
using DTC.Converters;

namespace DTC.Popups
{
    /// <summary>
    /// Interaction logic for BoxPopup.xaml
    /// </summary>
    public partial class BoxPopup : Window
    {
        public BoxPopup()
        {
            InitializeComponent();
			this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            box = new DTCBox();
            MainGrid.DataContext = Box;
            drugs = new ObservableCollection<DTCDrug>(App.DBI.GetAllDrugs());
            issueForms = new ObservableCollection<DTCIssueForm>(App.DBI.GetAllIssueForms());
            manufacturers = new ObservableCollection<DTCManufacturer>(App.DBI.GetAllManufacturers());
            IssueFormComboBox.ItemsSource = issueForms;
            DrugComboBox.ItemsSource = drugs;
            isNew = true;
        }

        private bool isNew;
        private ObservableCollection<DTCDrug> drugs;
        private ObservableCollection<DTCIssueForm> issueForms;
        private ObservableCollection<DTCManufacturer> manufacturers;

        private DTCBox box;
        public DTCBox Box
        {
            get
            {
                return box;
            }
            set
            {
                if (box != value)
                {
                    box = value;
                    MainGrid.DataContext = box;
                    DrugComboBox.SelectedItem = box.Drug;
                    if (box.DTCManufacturer != null)
                        ManufacturerComboBox.SelectedItem = box.DTCManufacturer;
                    if (box.DTCDrugUnit != null)
                        IssueFormComboBox.SelectedItem = box.IssueForm;
                    UnitSizeTextBox.Text = box.DTCDrugUnit.FormatedValue;
                    UnitCountTextBox.Text = box.UnitCount.ToString();
                    isNew = false;
                }
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.DialogResult == true)
            {

                #region Проверка полноты введенных данных
                if (!RequeredDataEntered())
                {
                    WarningPopup wp = new WarningPopup();
                    wp.Title = "Внимание";
                    wp.Message = "Вы не указали необходимые данные";
                    e.Cancel = true;
                    App.DBI.ChangeCancel();
                    wp.ShowDialog();
                    return;
                }
                #endregion

                #region Проверка данных
                string WarningMessage = EnteredDataValid();
                if(WarningMessage.Length != 0)
                {
                    WarningPopup wp = new WarningPopup();
                    wp.Title = "Внимание";
                    wp.Message = "Вы не указали необходимые данные";
                    e.Cancel = true;
                    App.DBI.ChangeCancel();
                    wp.ShowDialog();
                    return;
                }
                #endregion


                #region Формирование упаковки
                box.DTCDrugUnit = new DTCDrugUnit();

                if (SetDrug() == false)
                {
                    e.Cancel = true;
                    WarningPopup wp = new WarningPopup();
                    wp.Title = "Ошибка";
                    wp.Message = "Произошла незивестная ошибка. Данные не сохраненны";
                    App.DBI.ChangeCancel();
                    return;
                }
                SetManufacturer();
                if (SetIssueForm() == false)
                {
                    e.Cancel = true;
                    WarningPopup wp = new WarningPopup();
                    wp.Title = "Ошибка";
                    wp.Message = "Необходимо указать форму выпуска препарата";
                    App.DBI.ChangeCancel();
                    return;
                }
                if (box.DTCDrugUnit.DTCIssueForm.IsDiscret == true)
                {
                    box.DTCDrugUnit.FormatedValue = UnitSizeTextBox.Text;
                    int count;
                    int.TryParse(UnitCountTextBox.Text, out count);
                    box.UnitCount = count;
                }
                else
                {
                    box.DTCDrugUnit.FormatedValue = "1";
                    double count = (double)(new SiStringToDoubleConverter()).ConvertFrom(UnitCountTextBox.Text);
                    box.UnitCount = count;
                }
                DTCDrug drug = box.DTCDrugUnit.DTCDrug;
                DTCDrugUnit delUnit = null;
                foreach (DTCDrugUnit du in drug.DTCDrugUnits)
                {
                    if(du != box.DTCDrugUnit)
                    {
                        if (du.DTCDrug == box.DTCDrugUnit.DTCDrug
                            &&
                            du.DTCIssueForm == box.DTCDrugUnit.DTCIssueForm
                            &&
                            du.Value == box.DTCDrugUnit.Value)
                        {
                            delUnit = box.DTCDrugUnit;
                            box.DTCDrugUnit = du;
                            break;
                        }
                    }
                }
                #endregion
                if(isNew)
                    App.DBI.Db.DTCBoxes.InsertOnSubmit(box);
                App.DBI.Db.SubmitChanges();
                if (delUnit != null)
                {
                    App.DBI.Db.DTCDrugUnits.DeleteOnSubmit(delUnit);
                    App.DBI.Db.SubmitChanges();
                }
            }
            else
                App.DBI.ChangeCancel();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            new DTC.Resources.TextBoxBindingValidationSetter().PrepareBinding(MainGrid);
        }

        private void MesaureForUnitValueComboBox_TextInput(object sender, TextCompositionEventArgs e)
        {

        }

        private bool RequeredDataEntered()
        {
            if (DrugComboBox.SelectedIndex == -1 && DrugComboBox.Text.Length == 0)
                return false;
            if (IssueFormComboBox.SelectedIndex == -1 && IssueFormComboBox.Text.Length == 0)
                return false;
            if (UnitCountTextBox.Text.Length == 0)
                return false;
            if (((DTCIssueForm)IssueFormComboBox.SelectedItem).IsDiscret == true)
                if (UnitSizeTextBox.Text.Length == 0)
                    return false;
            return true;
        }

        private string EnteredDataValid()
        {
            return "";
        }

        private bool SetDrug()
        {
            DTCDrug selectedDrug;
            if (DrugComboBox.SelectedIndex == -1 && DrugComboBox.Text.Length != 0)
            {
                selectedDrug = new DTCDrug() { Name = DrugComboBox.Text };
                App.DBI.Db.DTCDrugs.InsertOnSubmit(selectedDrug);
            }
            else if (DrugComboBox.SelectedIndex != -1)
                selectedDrug = (DTCDrug)DrugComboBox.SelectedItem;
            else return false;
            if (box.DTCDrugUnit.DTCDrug != null)
                if (box.DTCDrugUnit.DTCDrug == selectedDrug)
                    box.DTCDrugUnit = new DTCDrugUnit();
            box.DTCDrugUnit.DTCDrug = selectedDrug;
            return true;
        }

        private void SetManufacturer()
        {
            DTCManufacturer selectedManufacturer = null;
            if (ManufacturerComboBox.SelectedIndex == -1 && ManufacturerComboBox.Text.Length != 0)
            {
                selectedManufacturer = new DTCManufacturer() { Name = ManufacturerComboBox.Text };
                App.DBI.Db.DTCManufacturers.InsertOnSubmit(selectedManufacturer);
            }
            else if (ManufacturerComboBox.SelectedIndex != -1)
            {
                selectedManufacturer = (DTCManufacturer)ManufacturerComboBox.SelectedItem;
            }
            
            if(selectedManufacturer != null)
                box.DTCManufacturer = selectedManufacturer;
        }

        private bool SetIssueForm()
        {
            
            if (IssueFormComboBox.SelectedIndex == -1)
                return false;
            DTCIssueForm selectedIssueForm = (DTCIssueForm)IssueFormComboBox.SelectedItem;
            if (box.DTCDrugUnit.DTCIssueForm != null)
            {
                if (box.DTCDrugUnit.DTCIssueForm != selectedIssueForm)
                {
                    DTCDrugUnit tmp = box.DTCDrugUnit;
                    box.DTCDrugUnit = new DTCDrugUnit();
                    box.DTCDrugUnit.DTCDrug = tmp.DTCDrug;
                    box.DTCDrugUnit.Value = tmp.Value;
                }
            }
            box.DTCDrugUnit.DTCIssueForm = selectedIssueForm;
            return true;
        }

        private void IssueFormComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IssueFormComboBox.SelectedIndex == -1)
            {
                UnitSizeTextBox.Text = "1";
                UnitCountTextBox.Text = "0";
                UnitValueBlock.Visibility = Visibility.Collapsed;
                UnitCountBlock.Visibility = Visibility.Collapsed;
            }
            else
            {
                if (((DTCIssueForm)IssueFormComboBox.SelectedItem).IsDiscret == true)
                {
                    UnitSizeTextBox.Text = "";
                    UnitCountTextBox.Text = "";
                    UnitValueBlock.Visibility = Visibility.Visible;
                    UnitCountBlock.Visibility = Visibility.Visible;
                }
                else
                {
                    UnitCountTextBox.Text = "";
                    UnitSizeTextBox.Text = "";
                    UnitValueBlock.Visibility = Visibility.Collapsed;
                    UnitCountBlock.Visibility = Visibility.Visible;
                }
            }
        }

    }
}
